﻿using HomeCareLibrary.Constants;
using HomeCareLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using HomeCareLibrary.AppService;
using HomeCareLibrary.Core.Dtos;
using HomeCareLibrary.Core.DataContracts;
using AutoMapper;
using HomeCareLibrary.Filters;
using System.IO;
using System.Net;
using System.Text;
using HomeCareLibrary.Core.JsonObjects;



namespace HomeCareLibrary.Controllers
{
    //[HybridAuthorize] //comment on(5.2.2014)
    public class PersonalizationController : BaseController
    {
        private homewizard_test2databaseEntities db = new homewizard_test2databaseEntities();
        /// <summary>
        ///   Session[SessionConstants.CHANGE_DWELLINGTYPE] = null; //this is null because user have not change the dwelling type.
        ///   //Session[SessionConstants.USER_ID] and Session[SessionConstants.HOME_NUMBER] are come from UpdatePersonalization() and  UpdateHomeNumber(HomeNumberModel model)
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var getSessionUserId = TempData["getUserSessionId"];

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            
            
            var model = new UserDetailIDModel();

            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;

            String strIphoneApp = String.Empty;
            String strAndriodApp = String.Empty;
            String finalSessionMode = String.Empty;
            if (Session[SessionConstants.MODE] != null)
            {
                if (Session[SessionConstants.MODE].ToString() == ApplicationModeConstants.IPHONE_APP)
                {
                    finalSessionMode = ApplicationModeConstants.IPHONE_APP;
                }
                else if (Session[SessionConstants.MODE].ToString() == ApplicationModeConstants.ANDROID_APP)
                {
                    finalSessionMode = ApplicationModeConstants.ANDROID_APP;
                }
            }
            
            if (Session[SessionConstants.USER_ID] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]

                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());

                Int32 homeNumber = 1;
                DataRepository entities = new DataRepository();
                if (Session[SessionConstants.HOME_NUMBER] == null)
                {
                    var getHomeNumber = entities.getMultipleHomesByUserID(userId);
                    homeNumber = Convert.ToInt32(getHomeNumber);
                    Session[SessionConstants.HOME_NUMBER] = homeNumber;
                }

                else if (Convert.ToInt32(Session[SessionConstants.HOME_NUMBER]) == 0)
                {

                    var getHomeNumber = entities.getMultipleHomesByUserID(userId);
                    homeNumber = Convert.ToInt32(getHomeNumber);
                    Session[SessionConstants.HOME_NUMBER] = homeNumber;
                }
                else
                {
                    homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());
                }



                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                GetUserHomeRequest objGetUserHomeRequest = new GetUserHomeRequest();
                objGetUserHomeRequest.UserId = userId;
                var getUserHome = (from d in objPersonalisationAppService.GetUserHomes(objGetUserHomeRequest) where d.home_number == homeNumber select d).SingleOrDefault();

                var getUserHomeModel = (CTGetUserHomesDto)getUserHome;
                Mapper.CreateMap<CTGetUserHomesDto, UserDetailIDModel>();
                Mapper.Map<CTGetUserHomesDto, UserDetailIDModel>(getUserHomeModel, model);

                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "DT");

                #endregion

                #region[Bind Dwelling Type(1)]
                model.listDwellingTypes = objPersonalisationAppService.GetDwellingTypes();
                ViewBag.getDwellingType = new SelectList(model.listDwellingTypes, "dwelling_code", "dwelling_type", model.dwelling_type);
                #endregion


                return View("Index", model);
               
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }



        }



        public ActionResult DwellingType()
        {
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;


            var model = new UserDetailIDModel();
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]


                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                Int32 homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());

                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                GetUserHomeRequest objGetUserHomeRequest = new GetUserHomeRequest();
                objGetUserHomeRequest.UserId = userId;
                var getUserHome = (from d in objPersonalisationAppService.GetUserHomes(objGetUserHomeRequest) where d.home_number == homeNumber select d).SingleOrDefault();
                var getUserHomeModel = (CTGetUserHomesDto)getUserHome;
                Mapper.CreateMap<CTGetUserHomesDto, UserDetailIDModel>();
                Mapper.Map<CTGetUserHomesDto, UserDetailIDModel>(getUserHomeModel, model);

                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "DT");

                #endregion

                #region[Bind Dwelling Type(1)]

                model.listDwellingTypes = objPersonalisationAppService.GetDwellingTypes();
                ViewBag.getDwellingType = new SelectList(model.listDwellingTypes, "dwelling_code", "dwelling_type", model.dwelling_type);
                #endregion
                return PartialView(model);
            }
            else
            {
                return Content("");
            }



        }

        public ActionResult HomeFeatures()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            
           
            
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                 #region[One AppService]

                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                Int32 homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());
                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();

                Int32 dwellingType=0;
                if (Session[SessionConstants.CHANGE_DWELLINGTYPE] != null)
                {
                    dwellingType = Convert.ToInt32(Session[SessionConstants.CHANGE_DWELLINGTYPE].ToString());
                }

                else
                {
                    GetUserHomeRequest objGetUserHomeRequest = new GetUserHomeRequest();
                    objGetUserHomeRequest.UserId = userId;
                    dwellingType = (from d in objPersonalisationAppService.GetUserHomes(objGetUserHomeRequest) where d.home_number == homeNumber select d.dwelling_type).FirstOrDefault();
                }
                var getHomeFeatures = objPersonalisationAppService.GetFeaturesByUserIdHomeNumberDwellingType(userId, homeNumber,dwellingType); 

                #endregion

                return PartialView("homefeatures", getHomeFeatures);
            }

            else
            {
                return Content("");

            }


        }

        public ActionResult LocalClimate()
        {

            

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            
            var model = new UserDetailIDModel();
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;
            Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY] = null;
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                Int32 homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]

                GetKLByUserIdHomeNumberRequest objGetKLByUserIdHomeNumberRequest = new GetKLByUserIdHomeNumberRequest();
                objGetKLByUserIdHomeNumberRequest.UserId = userId;
                objGetKLByUserIdHomeNumberRequest.HomeNumber = homeNumber;

                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                var getLocationGoalsKnowPriorityData = objPersonalisationAppService.GetLocationGoalsKnowPriorityByUserIdHomeNumber(objGetKLByUserIdHomeNumberRequest);
                if (getLocationGoalsKnowPriorityData["userId"] != null)
                {
                    model.user_id = Convert.ToInt32(getLocationGoalsKnowPriorityData["userId"].ToString());

                }
                if (getLocationGoalsKnowPriorityData["homeNumber"] != null)
                {
                    model.home_number = Convert.ToInt32(getLocationGoalsKnowPriorityData["homeNumber"].ToString());
                }
                model.ps_country = getLocationGoalsKnowPriorityData["psCountry"];
                model.ps_state_province = getLocationGoalsKnowPriorityData["psStateProvince"];

                model.ps_goal_string = getLocationGoalsKnowPriorityData["psGoalString"];
                if (getLocationGoalsKnowPriorityData["psPriority"] != null)
                {
                    model.ps_priority = Convert.ToInt32(getLocationGoalsKnowPriorityData["psPriority"].ToString());
                }

                if (getLocationGoalsKnowPriorityData["psKnowledgeLevel"] != null)
                {
                    model.ps_knowledge_level = Convert.ToInt32(getLocationGoalsKnowPriorityData["psKnowledgeLevel"].ToString());
                }


                Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY] = model;
              
                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "LC");


                #endregion


                #region[Bind Local Climate-Country,State(3)]
                //Start Bind Country State Dropdowns
                var selectedCountry = "US";
                var selectedState = "";
                if (!String.IsNullOrEmpty(model.ps_country))
                {
                    selectedCountry = model.ps_country;
                }
                if (!String.IsNullOrEmpty(model.ps_state_province))
                {
                    selectedState = model.ps_state_province;
                }



                var location = objPersonalisationAppService.GetCountryStates().Select(e => new { e.country_name, e.country }).Distinct().OrderByDescending(e => e.country_name);



                var state = (from s in objPersonalisationAppService.GetCountryStates()
                             where s.country == selectedCountry
                             select s);

                ViewBag.Country = new SelectList(location, "country", "country_name", selectedCountry);

                ViewData["optional"] = "-Select state or region-";

                if (selectedCountry == "CAN")
                {
                    ViewData["optional"] = "-Select Province-";
                }

                if (!String.IsNullOrEmpty(selectedState))
                {
                    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name", selectedState);
                }
                else
                {
                    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name");
                }

                //end Country State Dropdowns
                #endregion

                return PartialView("localclimate", model);
            }
            else
            {
                return Content("");

            }
        }

        public ActionResult Goals()
        {

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            
            var model = new UserDetailIDModel();
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]

                if (Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY] != null)
                {
                    model = (UserDetailIDModel)Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY];
                }
              

                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "GO");

                #endregion


                return PartialView("goals", model);
            }
            else
            {
                return Content("");

            }
        }

        public ActionResult KnowledgeLevel()
        {

            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            
            var model = new UserDetailIDModel();
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]


                if (Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY] != null)
                {
                    model = (UserDetailIDModel)Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY];
                }

                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "KL");

                #endregion

                return PartialView("knowledgelevel", model);
            }
            else
            {
                return Content("");

            }
        }

        public ActionResult Priority()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing
            
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            var model = new UserDetailIDModel();
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]


                if (Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY] != null)
                {
                    model = (UserDetailIDModel)Session[SessionConstants.PERSONALIZATION_LOCATION_GOALS_KNOW_PRIORITY];
                }

                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "PR");

                #endregion

                return PartialView("priority", model);
            }
            else
            {
                return Content("");

            }
        }

        public ActionResult MonthlyAlert()
        {

            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP;  //Only for Testing

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            
            var model = new UserDetailIDModel();
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = null;
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                Int32 homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());


                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                GetKLByUserIdHomeNumberRequest objGetKLByUserIdHomeNumberRequest = new GetKLByUserIdHomeNumberRequest();
                objGetKLByUserIdHomeNumberRequest.UserId = userId;
                objGetKLByUserIdHomeNumberRequest.HomeNumber = homeNumber;

                var getPriority = objPersonalisationAppService.GetMonthlyAlertSettingsByUserIdHomeNumber(objGetKLByUserIdHomeNumberRequest).SingleOrDefault();
                Mapper.CreateMap<CTGetMonthlyAlertSettingsByUserIdHomeNumberDto, UserDetailIDModel>();
                Mapper.Map<CTGetMonthlyAlertSettingsByUserIdHomeNumberDto, UserDetailIDModel>(getPriority, model);

                //if there are null values in the Model then pick up from Default
                GetDefaultTypes(model, "ML");

                #endregion

                #region[App Bind]
                ViewBag.getWeekoftheMonth = new SelectList(GetWeekOfTheMonth(), "Value", "Text", model.app_mo_alert_week);
                ViewBag.getDayoftheWeek = new SelectList(GetDayOfTheWeek(), "Value", "Text", model.app_mo_alert_day);
                ViewBag.getTimeoftheDay = new SelectList(GetTimeOfTheDay(), "Value", "Text", model.app_mo_alert_hour);
                #endregion


                return PartialView("monthlyalert", model);
            }
            else
            {
                return Content("");

            }
        }

        public ActionResult GettingStarted()
        {
            return View();
        }
        public ActionResult UpdatePersonalization()
        {
            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];
           
            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;


            if (Session[SessionConstants.USER_ID] != null)
            {

                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());

                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                GetUserHomeRequest objGetUserHomeRequest = new GetUserHomeRequest();
                objGetUserHomeRequest.UserId = userId;
                var getHome = objPersonalisationAppService.GetUserHomes(objGetUserHomeRequest);

                Int32 countGetHome = getHome.Count();
                if (countGetHome > 1)
                {
                    if (Session[SessionConstants.HOME_NUMBER] != null)
                    {
                        ViewBag.getHome = new SelectList(getHome, "home_number", "home_name", Session[SessionConstants.HOME_NUMBER].ToString());
                    }
                    else
                    {
                        ViewBag.getHome = new SelectList(getHome, "home_number", "home_name", "");
                    }

                   
                }
                else
                {
                    var getSingleHome = (from d in db.User_Details
                                         where d.user_id == userId
                                         orderby d.home_number
                                         select d.home_number).SingleOrDefault();

                    ViewBag.getHome = null;
                    ViewBag.getSingleHome = Convert.ToInt32(getSingleHome.ToString());
                }

                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }


        public ActionResult UpdateHomeNumber(HomeNumberModel model)
        {
            //viewBag does not retain values between controller. so used TempData.

             if (Session[SessionConstants.USER_ID] != null)
             {
                 TempData["getUserSessionId"] = Session[SessionConstants.USER_ID].ToString();
             }
            else
            {
                TempData["getUserSessionId"] = "No Session userId";
            }
            
            Int32 homeNumber = model.ID;
            Session[SessionConstants.HOME_NUMBER] = homeNumber;
            return RedirectToAction("Index", "Personalization");
            
        }

        public ActionResult ChangeDwellingType(int id)
        {
            Session[SessionConstants.CHANGE_DWELLINGTYPE] = id; //user has changed the dwelling type.
            //String getCommaSeparatedDefault = String.Empty;

            //check user change his dwelling type or not
            //if (Session[SessionConstants.CHANGE_DWELLINGTYPE] != null) //means user changed his dwelling type
            //{
            //    var service = new PersonalisationAppService();
            //    Int32 intDwellingCode = Convert.ToInt32(Session[SessionConstants.CHANGE_DWELLINGTYPE].ToString());

            //    var defaultDwellingFeatures = service.GetDefaultFeaturesByDwellingCode(new GetFeaturesByDwellingTypeRequest { DwellingCode = intDwellingCode });
            //    getCommaSeparatedDefault = string.Join(",", defaultDwellingFeatures.Select(x => string.Format("'{0}'", x.feature_code)));
            //}
            //return Json(getCommaSeparatedDefault, JsonRequestBehavior.AllowGet);

            return Json("", JsonRequestBehavior.AllowGet);

        }

        [HttpGet]
        public ActionResult getStatesbyCountry(string country)
        {
            //perform your action here
            var states = (from s in db.Country_State
                          where s.country == country
                          select s).ToList();
            var result = (from s in states
                          select new { id = s.state_province_code, name = s.state_or_province_name })
                          .ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }


        public void UpdateDefaultValues(UserDetailIDModel model)
        {
            var userDetail = (from u in db.User_Details
                              where u.user_id == model.user_id && u.home_number == model.home_number
                              select u).First();

            //we will get the values from default, if there are null values.
            UserDetailIDModel getUserHomeDefault = new UserDetailIDModel();
            DataRepository entities = new DataRepository();
            getUserHomeDefault = entities.GetPersonalizationDefault();

            if (String.IsNullOrEmpty(model.home_name))
            {
                if (userDetail.home_name == null)
                {
                    model.home_name = getUserHomeDefault.home_name;
                }
                else
                {
                    model.home_name = userDetail.home_name;
                }
            }
            if (model.dwelling_type == 0)
            {
                if (userDetail.dwelling_type == 0)
                {
                    model.dwelling_type = getUserHomeDefault.dwelling_type;
                }
                else
                {
                    model.dwelling_type = userDetail.dwelling_type;
                }
            }
            if (String.IsNullOrEmpty(model.featurestring))
            {

                if (String.IsNullOrEmpty(userDetail.featurestring))
                {
                    model.featurestring = getUserHomeDefault.featurestring.Trim();
                }
                else
                {
                    model.featurestring = userDetail.featurestring.Trim();
                }
            }
            else
            {
                model.featurestring = model.featurestring.Trim();
            }
            if (model.ps_priority == 0 || model.ps_priority == null)
            {
                if (userDetail.ps_priority == 0 || userDetail.ps_priority == null)
                {
                    model.ps_priority = getUserHomeDefault.ps_priority;
                }
                else
                {
                    model.ps_priority = userDetail.ps_priority;
                }
            }
            if (model.ps_knowledge_level == 0 || model.ps_knowledge_level == null)
            {
                if (userDetail.ps_knowledge_level == 0 || model.ps_knowledge_level == null)
                {
                    model.ps_knowledge_level = getUserHomeDefault.ps_knowledge_level;
                }
                else
                {
                    model.ps_knowledge_level = userDetail.ps_knowledge_level;
                }
            }
            if (String.IsNullOrEmpty(model.ps_country))
            {
                if (String.IsNullOrEmpty(userDetail.ps_country))
                {
                    model.ps_country = getUserHomeDefault.ps_country;
                }
                else
                {
                    model.ps_country = userDetail.ps_country;
                }
            }
            if (String.IsNullOrEmpty(model.ps_state_province))
            {
                if (String.IsNullOrEmpty(userDetail.ps_state_province))
                {
                    model.ps_state_province = getUserHomeDefault.ps_state_province;
                }
                else
                {
                    model.ps_state_province = userDetail.ps_state_province;
                }
            }
            if (String.IsNullOrEmpty(model.ps_goal_string))
            {
                if (String.IsNullOrEmpty(userDetail.ps_goal_string))
                {
                    model.ps_goal_string = getUserHomeDefault.ps_goal_string;
                }
                else
                {
                    model.ps_goal_string = userDetail.ps_goal_string;
                }
            }


            var userIds = (from u in db.User_ID
                           where u.user_id1 == model.user_id
                           select u).First();

            //if (String.IsNullOrEmpty(model.web_mo_alert_email))
            //{
            //    model.web_mo_alert_email = userIds.web_mo_alert_email;
            //}

            if (model.app_mo_alert_week == null)
            {
                if (userIds.app_mo_alert_week == null)
                {

                    model.app_mo_alert_week = 0;
                }
                else
                {
                    model.app_mo_alert_week = userIds.app_mo_alert_week;
                }
            }
            if (model.app_mo_alert_day == null)
            {

                if (userIds.app_mo_alert_day == null)
                {

                    model.app_mo_alert_day = 0;
                }
                else
                {
                    model.app_mo_alert_day = userIds.app_mo_alert_day;
                }
            }

            if (model.app_mo_alert_hour == null)
            {
                if (userIds.app_mo_alert_hour == null)
                {

                    model.app_mo_alert_hour = 0;
                }
                else
                {
                    model.app_mo_alert_hour = userIds.app_mo_alert_hour;
                }
            }

            if (model.app_mo_alert_badge == null)
            {

                if (userIds.app_mo_alert_badge == null)
                {
                    model.app_mo_alert_badge = 0;
                }
                else
                {
                    model.app_mo_alert_badge = userIds.app_mo_alert_badge;
                }
            }

            if (model.app_mo_alert_popup == null)
            {
                if (userIds.app_mo_alert_popup == null)
                {
                    model.app_mo_alert_popup = 0;
                }
                else
                {
                    model.app_mo_alert_popup = userIds.app_mo_alert_popup;
                }
            }
        }


        public ActionResult UpdateAllPersonalization(UserDetailIDModel model)
        {
            if (Session[SessionConstants.HOME_NUMBER] != null)
            {
                model.home_number = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());
            }

            UpdateDefaultValues(model);

            PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
            PersonalizationData objpersonlisationData = new PersonalizationData();

            Mapper.CreateMap<UserDetailIDModel, PersonalizationData>().ForMember(x => x.UserId, o => o.MapFrom(s => s.user_id)).ForMember(x => x.HomeNumber, o => o.MapFrom(s => s.home_number)).ForMember(x => x.HomeName, o => o.MapFrom(s => s.home_name)).ForMember(x => x.DwellingType, o => o.MapFrom(s => s.dwelling_type)).ForMember(x => x.FeatureString, o => o.MapFrom(s => s.featurestring)).ForMember(x => x.KnowledgeLevel, o => o.MapFrom(s => s.ps_knowledge_level)).ForMember(x => x.Country, o => o.MapFrom(s => s.ps_country)).ForMember(x => x.Goal, o => o.MapFrom(s => s.ps_goal_string)).ForMember(x => x.WebMOAlertEmail, o => o.MapFrom(s => s.web_mo_alert_email)).ForMember(x => x.AppMoAlertWeek, o => o.MapFrom(s => s.app_mo_alert_week)).ForMember(x => x.AppMoAlertDay, o => o.MapFrom(s => s.app_mo_alert_day)).ForMember(x => x.AppMoAlertHour, o => o.MapFrom(s => s.app_mo_alert_hour)).ForMember(x => x.AppMoAlertBadge, o => o.MapFrom(s => s.app_mo_alert_badge)).ForMember(x => x.AppMoAlertPopup, o => o.MapFrom(s => s.app_mo_alert_popup)).ForMember(x => x.Priority, o => o.MapFrom(s => s.ps_priority)).ForMember(x => x.StateProvince, o => o.MapFrom(s => s.ps_state_province));
            Mapper.Map<UserDetailIDModel, PersonalizationData>(model, objpersonlisationData);
            objPersonalisationAppService.UpdatePersonalization(objpersonlisationData);

            return RedirectToAction("Done");
        }

        public ActionResult Done()
        {
            CTGetUserHomesDto objCTGetUserHomesDto=new CTGetUserHomesDto();
            
            if (Session[SessionConstants.USER_ID] != null && Session[SessionConstants.HOME_NUMBER] != null)
            {
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                Int32 homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());

                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                GetUserHomeRequest objGetUserHomeRequest = new GetUserHomeRequest();
                objGetUserHomeRequest.UserId = userId;
                objCTGetUserHomesDto = (CTGetUserHomesDto)(from d in objPersonalisationAppService.GetUserHomes(objGetUserHomeRequest) where d.home_number == homeNumber select d).SingleOrDefault();
               
            }
            var getHomeValue = String.Empty;
            if (objCTGetUserHomesDto != null)
            {
                 getHomeValue= objCTGetUserHomesDto.home_name;
            }
            ViewBag.getHomeName = getHomeValue;
            
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            return View();
        }

        [HttpGet]
        public ActionResult featureDetail(string id)
        {
            var service = new PersonalisationAppService();
            var featureDetail = service.GetFeatureById(id);
            return PartialView("featureDetail", featureDetail);

        }

        #region[Common Functions]
        public SelectListItem[] GetWeekOfTheMonth()
        {
            return new[]
        {
           new SelectListItem { Value = "1", Text = "First week of the month" },
           new SelectListItem { Value = "2", Text = "Second week of the month" },
           new SelectListItem { Value = "3", Text = "Third week of the month" },
           new SelectListItem { Value = "4", Text = "Fourth week of the month" },
          
        };

        }
        public SelectListItem[] GetDayOfTheWeek()
        {
            return new[]
        {
           new SelectListItem { Value = "1", Text = "Sunday" },
           new SelectListItem { Value = "2", Text = "Monday" },
           new SelectListItem { Value = "3", Text = "Tuesday" },
           new SelectListItem { Value = "4", Text = "Wednesday" },
           new SelectListItem { Value = "5", Text = "Thursday" },
           new SelectListItem { Value = "6", Text = "Friday" },
           new SelectListItem { Value = "7", Text = "Saturday" },
          
        };

        }

        public SelectListItem[] GetTimeOfTheDay()
        {
            return new[]
        {
          
           new SelectListItem { Value = "0", Text = "midnight" },
           new SelectListItem { Value = "1", Text = "1 am" },
           new SelectListItem { Value = "2", Text = "2 am" },
           new SelectListItem { Value = "3", Text = "3 am" },
           new SelectListItem { Value = "4", Text = "4 am" },
           new SelectListItem { Value = "5", Text = "5 am" },
           new SelectListItem { Value = "6", Text = "6 am" },
           new SelectListItem { Value = "7", Text = "7 am" },
           new SelectListItem { Value = "8", Text = "8 am" },
           new SelectListItem { Value = "9", Text = "9 am" },
           new SelectListItem { Value = "10", Text = "10 am" },
           new SelectListItem { Value = "11", Text = "11 am" },
           new SelectListItem { Value = "12", Text = "12 pm" },
           new SelectListItem { Value = "13", Text = "1 pm" },
           new SelectListItem { Value = "14", Text = "2 pm" },
           new SelectListItem { Value = "15", Text = "3 pm" },
           new SelectListItem { Value = "16", Text = "4 pm" },
           new SelectListItem { Value = "17", Text = "5 pm" },
           new SelectListItem { Value = "18", Text = "6 pm" },
           new SelectListItem { Value = "19", Text = "7 pm" },
           new SelectListItem { Value = "20", Text = "8 pm" },
           new SelectListItem { Value = "21", Text = "9 pm" },
           new SelectListItem { Value = "22", Text = "10 pm" },
           new SelectListItem { Value = "23", Text = "11 pm" }
           
        };

        }

        #endregion


        public ActionResult DwellingMobile()
        {
            return View();
        }

        #region [WebView Mobiles]

        public ActionResult UpdatePriority(String user_id, String PriorityValueUpdate, String Condition)
        {

            String result = "0";

            if (!String.IsNullOrEmpty(user_id))
            {
                Int32 userId = Convert.ToInt32(user_id);
                Int32 priorityValueUpdated = Convert.ToInt32(PriorityValueUpdate);

                var userIds = (from u in db.User_ID
                               where u.user_id1 == userId
                               select u).First();


                switch (Condition)
                {
                    case "Week":  //Update Week of the Month
                        userIds.app_mo_alert_week = priorityValueUpdated;
                        result = "1";
                        break;
                    case "Day":   //Update Day of that Week
                        userIds.app_mo_alert_day = priorityValueUpdated;
                        result = "1";
                        break;
                    case "Time":  //Update Time of that Day
                        userIds.app_mo_alert_hour = priorityValueUpdated;
                        result = "1";
                        break;
                    case "Badge": //Update Badge
                        userIds.app_mo_alert_badge = priorityValueUpdated;
                        result = "1";
                        break;

                    case "Alerts":  //Update Alerts
                        userIds.app_mo_alert_popup = priorityValueUpdated;
                        result = "1";
                        break;
                }

                db.User_ID.ApplyCurrentValues(userIds);
                db.SaveChanges();

            }
            return Json(result, JsonRequestBehavior.AllowGet);

        }


        public ActionResult AdminMonthlyAlerts()
        {

            //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP; //Only for Testing
            var model = new UserDetailIDModel();
            if (Session[SessionConstants.USER_ID] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID]


                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());

                DataRepository entities = new DataRepository();
                model = entities.getAdminMonthlyAlert_UserDetail(userId);
                #endregion

                #region[App Bind]
                ViewBag.getWeekoftheMonth = new SelectList(GetWeekOfTheMonth(), "Value", "Text", model.app_mo_alert_week);
                ViewBag.getDayoftheWeek = new SelectList(GetDayOfTheWeek(), "Value", "Text", model.app_mo_alert_day);
                ViewBag.getTimeoftheDay = new SelectList(GetTimeOfTheDay(), "Value", "Text", model.app_mo_alert_hour);
                #endregion
                return View("AdminMonthlyAlert", model);
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }


        }

        public ActionResult AdminPromoCode()
        {


            //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP; //Only for Testing

            var model = new PromoCodeModel();

            if (Session[SessionConstants.USER_ID] != null)
            {
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                DataRepository entities = new DataRepository();
                model = entities.getAdminPromoCode_UserID(userId);
                return View("adminpromocode", model);
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }



        }

        [HttpPost]
        public JsonResult UpdatePromoCode(PromoCodeModel model)
        {
            String result = "0";

            if (model.user_id > 0)
            {
                Int32 userId = model.user_id;

                DataRepository entities = new DataRepository();
                var getResult = entities.updatePromocode(userId, model.sponsor, model.DeletePromocode, model.ChangePromocode);

                return Json(new { JsonResult = getResult }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult DeletePromoCode(String userid, String Promocode, String DeletePromocode, String ChangePromocode)
        {
            String result = "0";

            if (!String.IsNullOrEmpty(userid))
            {
                Int32 userId = Convert.ToInt32(userid);

                DataRepository entities = new DataRepository();
                var getResult = entities.updatePromocode(userId, Promocode, DeletePromocode, ChangePromocode);

                return Json(new { JsonResult = getResult }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }


        public ActionResult AdminChangeLogin()
        {


            //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP; //Only for Testing

            var model = new LoginPasswordModel();

            if (Session[SessionConstants.USER_ID] != null)
            {

                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                DataRepository entities = new DataRepository();
                model = entities.getLogin_UserID(userId);
                return View(model);
            }

            else
            {
                return RedirectToAction("Login", "Home");
            }


        }


        [HttpPost]
        public JsonResult UpdateUserNamePassword(LoginPasswordModel model)
        {
            String result = "0";

            if (model.user_id > 0)
            {
                Int32 userId = model.user_id;
                DataRepository entities = new DataRepository();
                var getResult = entities.callsp_update(userId, model.user_name, model.password);
                return Json(new { JsonResult = getResult }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion


        public void GetDefaultTypes(UserDetailIDModel model, String page)
        {
            UserDetailIDModel getUserHomeDefault = new UserDetailIDModel();
            DataRepository entities = new DataRepository();

            getUserHomeDefault = entities.GetPersonalizationDefault();

            switch (page)
            {
                case "DT":
                    if (String.IsNullOrEmpty(model.home_name))
                    {
                        model.home_name = getUserHomeDefault.home_name;
                    }
                    if (model.home_number <= 0)
                    {
                        model.home_number = getUserHomeDefault.home_number;
                    }
                    if (model.dwelling_type <= 0)
                    {
                        model.dwelling_type = getUserHomeDefault.dwelling_type;
                    }
                    break;

                case "HF":

                    if (String.IsNullOrEmpty(model.featurestring))
                    {
                        model.featurestring = getUserHomeDefault.featurestring;
                    }
                    break;

                case "LC":
                    if (String.IsNullOrEmpty(model.ps_country))
                    {
                        model.ps_country = getUserHomeDefault.ps_country;
                    }
                    if (String.IsNullOrEmpty(model.ps_state_province))
                    {
                        model.ps_state_province = getUserHomeDefault.ps_state_province;
                    }
                    break;

                case "GO":
                    if (String.IsNullOrEmpty(model.ps_goal_string))
                    {
                        model.ps_goal_string = getUserHomeDefault.ps_goal_string;
                    }
                    break;
                case "KL":
                    if ((model.ps_knowledge_level == null) || (model.ps_knowledge_level <= 0))
                    {
                        model.ps_knowledge_level = getUserHomeDefault.ps_knowledge_level;
                    }
                    break;
                case "PR":
                    if ((model.ps_priority == null) || (model.ps_priority <= 0))
                    {
                        model.ps_priority = getUserHomeDefault.ps_priority;
                    }
                    break;

                case "ML":
                    if (model.app_mo_alert_badge == null)
                    {
                        model.app_mo_alert_badge = getUserHomeDefault.app_mo_alert_badge;
                    }
                    if (model.app_mo_alert_popup == null)
                    {
                        model.app_mo_alert_popup = getUserHomeDefault.app_mo_alert_popup;
                    }
                    if (model.app_mo_alert_week == null)
                    {
                        model.app_mo_alert_week = getUserHomeDefault.app_mo_alert_week;
                    }
                    if (model.app_mo_alert_day == null)
                    {
                        model.app_mo_alert_day = getUserHomeDefault.app_mo_alert_day;
                    }
                    if (model.app_mo_alert_hour == null)
                    {
                        model.app_mo_alert_hour = getUserHomeDefault.app_mo_alert_hour;
                    }
                    break;
            }



        }


        public ActionResult AddHome()
        {
            ViewBag.sessionIds = SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;


            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            

            return View();
        }


        public ActionResult PersonalizationAddHome()
        {
            if (Session[SessionConstants.USER_ID] != null)
            {
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                var getPersonalisationHome = objPersonalisationAppService.AddHome(userId);
                Int32 homeNumber = getPersonalisationHome.home_number;
                Session[SessionConstants.HOME_NUMBER] = homeNumber;
                Session[SessionConstants.ACTIVITY_TYPE] = ApplicationModeConstants.INITIAL_SETUP;
                return RedirectToAction("Index", "Personalization");
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        //public ActionResult HomeFeatureItems(String DwellingCode, String CategoryId)
        //{
        //    PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
        //    GetFeaturesByDwellingTypeRequest objGetFeaturesByDwellingTypeRequest = new GetFeaturesByDwellingTypeRequest();
        //    objGetFeaturesByDwellingTypeRequest.DwellingCode = 1; //currently set 1 for Testing
        //    var getDataByDwellingCode = objPersonalisationAppService.GetFeaturesByDwellingCode(objGetFeaturesByDwellingTypeRequest);
        //    return Json(getDataByDwellingCode, JsonRequestBehavior.AllowGet);
        //}

    }
}
